<template>
	<view class="form-container">

		<uni-section title="添加商品" type="line">
			<view class="example">
				<!-- 自定义表单校验 -->
				<uni-forms ref="customForm" :rules="customRules" :modelValue="customFormData">
					<uni-forms-item label="商品名称" required name="goodsName">
						<uni-easyinput v-model="customFormData.goodsName" placeholder="请输入商品名称" />
					</uni-forms-item>
					<uni-forms-item label="商品最低价" required name="lowPrice">
						<uni-easyinput v-model="customFormData.lowPrice" placeholder="请输入商品最低价" />
					</uni-forms-item>
					<uni-forms-item label="商品品牌" required name="category">
						<uni-data-checkbox v-model="customFormData.category" :localdata="section" />
					</uni-forms-item>

					<uni-forms-item label="添加规格" required name="attr">
						<uni-swipe-action ref="swipeAction">
							<uni-swipe-action-item class="swipe-item" v-for="(item, index) in swipeList"
								:right-options="item.options" @change="swipeChange($event, index)"
								@click="swipeClick($event, index)">
								<view class="content-box">
									<text class="content-text">{{ item.content }}</text>
								</view>
							</uni-swipe-action-item>
						</uni-swipe-action>
						<view class="picker-body" v-model="customFormData.commoditySpecValueRequests">
							<uni-combox class="combox" :candidates="first_level" placeholder="基本属性" v-model="choose_1">
							</uni-combox>
							<text class="te-xt"> - </text>
							<uni-combox class="combox" :candidates="second_level_1" placeholder="具体属性"
								v-model="choose_2">
							</uni-combox>
							<button class="add-button" @click="addItem()"><text class="add-text">添加</text></button>
						</view>


					</uni-forms-item>

					<view class="example-body">
						<view class="bg-default" v-if="imgBg === ''" @click="chooseImg(0)">
							<view class="" style="width: 70rpx; height: 70rpx;">
								<image class="my_img" :src="avatarUrl"></image>
							</view>
							<view class="text-default">添加商品图片</view>
						</view>

						<view class="add_img_view" v-else>
							<view class="add_img_item" @click="bindImg(0)">
								<image :src="imgBg"></image>
								<view class="add_close" @click.stop="deleteImg(0)">
									<uni-icons type="clear" size="15" color="#4977F9"></uni-icons>
								</view>
							</view>
						</view>
					</view>



					<uni-section title="添加具体规格" type="line">
						<uni-swipe-action ref="swipeAction">
							<uni-swipe-action-item class="swipe-item" v-for="(item, index) in swipeList_0"
								:right-options="item.options" @change="swipeChange($event, index)"
								@click="swipeClick($event, index)">
								<view class="content-box">
									<text class="content-text">{{ item.content }}</text>
								</view>
							</uni-swipe-action-item>
						</uni-swipe-action>
						<view class="picker-body">
							<uni-combox class="combox-1" :candidates="choose_2_list" placeholder="规格1" v-model="sku_1">
							</uni-combox>
							<text class="te-xt-1"> - </text>
							<uni-combox class="combox-1" :candidates="choose_2_list" placeholder="规格2" v-model="sku_2">
							</uni-combox>
							<text class="money-sg"> ￥ </text>
							<uni-easyinput class="money-input" v-model="sku_3" placeholder="输入商品价格" />
							<button class="add-button-1" @click="addItem_0()"><text class="add-text-1">+</text></button>
						</view>
					</uni-section>
				</uni-forms>
				<button type="primary" @click="submitIt()">提交</button>
			</view>
		</uni-section>
	</view>
</template>

<script>
	import uniCombox from '@/uni_modules/uni-combox/uni-combox.vue';
	export default {
		components: {
			uniCombox
		},
		data() {
			return {
				first_level: ['颜色', '尺寸'],
				second_level_1: ['白色', '黑色', '红色', 'S', 'M', 'L'],
				choose_1: '',
				choose_2: '',
				choose_2_list: [],
				attrList: [],
				sku_1: "",
				sku_2: "",
				sku_3: 0,
				skuList: [],
				submitList: [],
				swipeList: [],
				swipeList_0: [],
				// 上传默认图片
				avatarUrl: '../static/errorImage.jpg',
				// 背景图展示
				imgBg: '',
				// 背景图预览
				imgBgArray: [],
				// 背景图路径
				imgBgArr: '',
				// 上传的背景临时路径
				imgBgUrl: '',
				// 上传的背景图绝对路径
				imgBgArrUrl: '',
				spuId: 0,

				// model1: {
				// 	"shopId": 3,
				// 	"goodsName": "小米11",
				// 	"lowPrice": 5999.9,
				// 	"category": "小米",
				// 	"commoditySpecValueRequests": [{
				// 			"spec": "大小",
				// 			"values": ["小", "中", "大"]
				// 		},
				// 		{
				// 			"spec": "颜色",
				// 			"values": ["R", "G", "B"]
				// 		}
				// 	],
				// 	"commoditySkuSpecValueRequests": [{
				// 			"specValue1": "小",
				// 			"specValue2": "R",
				// 			"price": 5999.9
				// 		},
				// 		{
				// 			"specValue1": "中",
				// 			"specValue2": "G",
				// 			"price": 6999.9
				// 		},
				// 		{
				// 			"specValue1": "大",
				// 			"specValue2": "B",
				// 			"price": 7999.9
				// 		}
				// 	]
				// },
				imageStyles: {
					width: 64,
					height: 64,
					border: {
						radius: '50%'
					}
				},
				listStyles: {
					// 是否显示边框
					border: true,
					// 是否显示分隔线
					dividline: true,
					// 线条样式
					borderStyle: {
						width: 1,
						color: 'blue',
						style: 'dashed',
						radius: 2
					}
				},
				fileLists: [{
					url: 'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-dc-site/b7c7f970-517d-11eb-97b7-0dc4655d6e68.jpg',
					extname: 'png',
					name: 'shuijiao.png'
				}, {
					url: 'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-dc-site/b7c7f970-517d-11eb-97b7-0dc4655d6e68.jpg',
					extname: 'png',
					name: 'uniapp-logo.png'
				}, {
					url: 'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-dc-site/b7c7f970-517d-11eb-97b7-0dc4655d6e68.jpg',
					extname: 'png',
					name: 'shuijiao.png'
				}],


				// 多选数据源
				section: [{
					text: '华为',
					value: '华为'
				}, {
					text: '苹果',
					value: '苹果'
				}, {
					text: '小米',
					value: '小米'
				}],


				// 自定义表单数据
				customFormData: {
					shopId: 2,
					goodsName: '',
					lowPrice: '',
					category: '',
					commoditySpecValueRequests: [],
					commoditySkuSpecValueRequests: []
				},
				// 自定义表单校验规则
				customRules: {
					ID: {
						rules: [{
							required: true,
							errorMessage: '商品ID不能为空'
						}]
					},
					name: {
						rules: [{
							required: true,
							errorMessage: '商品名称不能为空'
						}]
					},
					price: {
						rules: [{
							required: true,
							errorMessage: '价格不能为空'
						}]
					},
					section: {
						rules: [{
								format: 'array'
							},
							{
								validateFunction: function(rule, value, data, callback) {
									if (value.length < 1) {
										callback('请至少勾选一个分类')
									}
									return true
								}
							}
						]
					}

				}
			}
		},
		computed: {
			// 处理表单排列切换
			alignment() {
				if (this.current === 0) return 'left'
				if (this.current === 1) return 'top'
				return 'left'
			}
		},
		onLoad() {},
		onReady() {
			// 设置自定义表单校验规则，必须在节点渲染完毕后执行
			this.$refs.customForm.setRules(this.customRules)
		},
		methods: {

			sendIt(list) {
				// uni.showModal({
				// 	content: '发送内容：' + JSON.stringify(sku)
				// });

				// uni.showModal({
				// 	content: '发送内容：' + JSON.stringify(this.customFormData)
				// });
				
				uni.request({
					url: 'http://localhost:8081/merchant/spu/insert',
					method: 'POST',
					data: JSON.stringify(this.customFormData),
					success: res => {
						console.log("成功发送");
						console.log(res);

						setTimeout(()=>{
							this.postImg(res.data.spuId,this.imgBg)
						},1000)
					}
				});
				
				

			},


			addSku() {
				this.skuList.push({
					sku_1: this.sku_1,
					sku_2: this.sku_2,
					sku_3: this.sku_3,
				})
			},

			submitIt() {
				this.submitList.push({
					name: this.customFormData.name,
					list: this.skuList,

				});
				this.sendIt(this.submitList);;
			},

			addItem() {
				this.customFormData.commoditySpecValueRequests.push({
						spec: this.choose_1,
						values: [this.choose_2]
					}),
					this.swipeList.push({
						options: [{
							text: '删除',
							style: {
								backgroundColor: 'rgb(255,58,49)'
							}
						}],
						content: this.choose_1 + " - " + this.choose_2,
					});
				//this.choose_1_list.push(this.choose_1);
				this.choose_2_list.push(this.choose_2);
				//this.choose_1 = "";

				this.choose_2 = "";
				this.$forceUpdate();

			},
			addItem_0() {
				this.customFormData.commoditySkuSpecValueRequests.push({
					specValue1: this.sku_1,
					specValue2: this.sku_2,
					price: this.sku_3
				})
				this.swipeList_0.push({
					options: [{
						text: '删除',
						style: {
							backgroundColor: 'rgb(255,58,49)'
						}
					}],
					content: this.sku_1 + " - " + this.sku_2 + "      ￥ " + this.sku_3,
				});
				this.addSku();
				this.$forceUpdate();

			},

			swipeChange(e, index) {
				console.log('返回：', e);
				console.log('当前索引：', index);
			},
			swipeClick(e, index) {
				let {
					content
				} = e;
				if (content.text === '删除') {
					uni.showModal({
						title: '提示',
						content: '是否删除',
						success: res => {
							if (res.confirm) {
								this.swipeList.splice(index, 1);
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				} else if (content.text === '添加') {
					if (this.swipeList.length < 10) {
						this.swipeList.push({
							options: [{
								text: '删除',
								style: {
									backgroundColor: 'rgb(255,58,49)'
								}
							}],
							content: this.attrList[this.attrList.length - 1],
						});
						uni.showToast({
							title: `添加了一条数据`,
							icon: 'none'
						});
					} else {
						uni.showToast({
							title: `最多添加十条数据`,
							icon: 'none'
						});
					}
				} else {
					uni.showToast({
						title: `点击了${e.content.text}按钮`,
						icon: 'none'
					});
				}
			},
			swipeClick_0(e, index) {
				let {
					content
				} = e;
				if (content.text === '删除') {
					uni.showModal({
						title: '提示',
						content: '是否删除',
						success: res => {
							if (res.confirm) {
								this.swipeList_0.splice(index, 1);
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				} else if (content.text === '添加') {
					if (this.swipeList_0.length < 10) {
						this.swipeList_0.push({
							options: [{
								text: '删除',
								style: {
									backgroundColor: 'rgb(255,58,49)'
								}
							}],
							content: this.attrList[this.attrList.length - 1],
						});
						uni.showToast({
							title: `添加了一条数据`,
							icon: 'none'
						});
					} else {
						uni.showToast({
							title: `最多添加十条数据`,
							icon: 'none'
						});
					}
				} else {
					uni.showToast({
						title: `点击了${e.content.text}按钮`,
						icon: 'none'
					});
				}
			},

			chooseImg() {
				const isIosTrue = uni.getStorageSync('IOS_FIRST_CAMERA')
				if (this.phoneType === 'ios' && isIosTrue !== 'false') {
				
					uni.setStorageSync('IOS_FIRST_CAMERA', 'false')
				}
				uni.chooseImage({
					sizeType: "compressed",
					// 选择图片的数量
					count: 1,
					success: res => {
						// console.log(res.tempFilePaths[0])
						this.imgBg = res.tempFilePaths[0]
						this.imgBgArray = res.tempFilePaths
						this.app_img(0, res)
					},
				})
			},
			app_img(num, res) {
				let that = this
				if (Number(num) === Number(res.tempFiles.length)) {
					return
				}
				let index = res.tempFiles[num].path.lastIndexOf(".")
				let img_type = res.tempFiles[num].path.substring(index, res.tempFiles[num].path.length)
				let img_yuanshi = res.tempFiles[num].path.substring(0, index)
				let d2 = new Date().getTime()
				plus.zip.compressImage({
					src: res.tempFiles[num].path,
					dst: img_yuanshi + d2 + img_type,
					quality: 10
				}, function(e) {
					that.imgBgArr = e.target
					that.postImg(1,that.imgBgArr)
					that.app_img(num + 1, res)
				})
			},

			deleteImg() {
				this.imgBg = ''
				this.imgBgAr = ''
				this.imgBgArrUrl = ''
			},
			// 点击图片
			bindImg() {
				if (this.imgBgArray.length !== 0) {
					console.log(index)
					uni.previewImage({
						urls: this.imgBgArray,
						current: 0
					})
				}
			},
			postImg(id,imgFilePaths) {
				
				uni.showModal({
				 	content: 'spuId' + JSON.stringify(id)+'d'+JSON.stringify(imgFilePaths)
				 });
				 
				uni.uploadFile({
					url: 'http://localhost:8081/spu/profilePhotoUpload',
					name:'file',
					filePath:imgFilePaths,
					formData:{
						spuId:id,
						mainPagePic:1,
					},
					
					success: (uploadFileRes) => {
						this.imgBgArrUrl = imgValue.data.absoluteUrl
						this.imgBgUrl = imgValue.data.url
					}
				});
			},


		}
	}
</script>

<style lang="scss">
	.combox {
		width: 40%;
	}

	.combox-1 {
		width: 20%;
	}

	.swipe-item {
		margin-top: 20upx;
	}

	.picker-body {
		display: flex;
		padding: 12px;
		background-color: #FFFFFF;

		.te-xt {
			margin-left: 20upx;
			margin-right: 20upx;
			font-size: 50upx;
		}

		.te-xt-1 {
			margin-left: 20upx;
			margin-right: 20upx;
			font-size: 50upx;
		}

		.money-sg {
			margin-left: 20upx;
			margin-right: 20upx;
			font-size: 50upx;
		}

		.add-button {
			width: 20%;
			height: 70upx;
			text-align: center;
			line-height: 60upx;
			margin-left: 20upx;

			.add-text {
				font-size: 10upx;
			}
		}

		.add-button-1 {
			width: 10%;
			height: 70upx;

			margin-left: 20upx;

			.add-text-1 {
				font-size: 40upx;
				line-height: 60upx;
				text-align: center;
			}
		}

	}



	.result-box {
		text-align: center;
		padding: 20px 0px;
		font-size: 16px;
	}


	.example {
		padding: 15px;
		background-color: #fff;
	}

	.segmented-control {
		margin-bottom: 15px;
	}

	.button-group {
		margin-top: 15px;
		display: flex;
		justify-content: space-around;
	}

	.form-item {
		display: flex;
		align-items: center;
	}

	.button {
		display: flex;
		align-items: center;
		height: 35px;
		margin-left: 10px;
	}

	.example-body {
		padding: 10px;
		padding-top: 0;
	}

	.custom-image-box {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
	}

	.text {
		font-size: 14px;
		color: #333;
	}
</style>
